package com.offcn.question.service.impl;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.offcn.common.utils.PageUtils;
import com.offcn.common.utils.Query;

import com.offcn.question.dao.QuestionDao;
import com.offcn.question.entity.QuestionEntity;
import com.offcn.question.service.QuestionService;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;


@Service("questionService")
public class QuestionServiceImpl extends ServiceImpl<QuestionDao, QuestionEntity> implements QuestionService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<QuestionEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)){
            wrapper.eq("TYPE",key).or().like("title",key);
        }
        IPage<QuestionEntity> page = this.page(
                new Query<QuestionEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public Map upload(MultipartFile file) {
        //map集合用于响应
        HashMap map = new HashMap<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取文件名字
        String filename = file.getOriginalFilename();
        //判断文件的后缀是否是xls或者xlsx
        if (!filename.matches("^.+\\.(?i)(xls)$") && !filename.matches("^.+\\.(?i)(xlsx)$")) {
            //失败
            map.put("result",false);
            map.put("msg","文件导入失败");
            map.put("num",0);
        }
        //创建一个集合用于装遍历出来数据
        List<QuestionEntity> list = new ArrayList<>();
        try {
            //读取文件
            InputStream inputStream = file.getInputStream();
            //创建一个工作簿将读取的流放入
            HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(inputStream));
            HSSFSheet sheet = workbook.getSheetAt(0);
            //读取有效的行数
            int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
            QuestionEntity questionEntity = null;
            for (int i = 0; i < physicalNumberOfRows; i++) {
                questionEntity = new QuestionEntity();
                HSSFRow row = sheet.getRow(i);
                questionEntity.setTitle(row.getCell(0).getStringCellValue());
                questionEntity.setAnswer(row.getCell(1).getStringCellValue());
                questionEntity.setLevel((int)row.getCell(2).getNumericCellValue());
                questionEntity.setType((long) row.getCell(3).getNumericCellValue());
                questionEntity.setSubTitle(row.getCell(4).getStringCellValue());
                questionEntity.setDisplayOrder((int)row.getCell(5).getNumericCellValue());
                questionEntity.setEnable((int)row.getCell(6).getNumericCellValue());
                list.add(questionEntity);
                this.save(questionEntity);
            }
            //正常执行完说明成功了
            map.put("result",true);
            map.put("msg","导入成功");
            map.put("num",list.size());
        } catch (IOException e) {
            map.put("result",false);
            map.put("msg","导入失败:"+e.getMessage());
            map.put("num",0);
        }
        return map;
    }
    @Override
    public Workbook download() {
        //创建工作簿
        Workbook workbook = new HSSFWorkbook();
        //创建表并定义名字
        Sheet sheet = workbook.createSheet("题库");
        //获取第0行
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("题目标题");
        row.createCell(1).setCellValue("题目解答");
        row.createCell(2).setCellValue("题目难度等级");
        row.createCell(3).setCellValue("排序");
        row.createCell(4).setCellValue("副标题");
        row.createCell(5).setCellValue("题目类型");
        row.createCell(6).setCellValue("是否显示");
        //将所有数据查出
        List<QuestionEntity> list = this.list();
        //遍历所有数并将他们写入表中
        for (int i = 0; i < list.size(); i++) {
            Row row1 = sheet.createRow(i + 1);
            row1.createCell(0).setCellValue(list.get(i).getTitle());
            row1.createCell(1).setCellValue(list.get(i).getAnswer());
            row1.createCell(2).setCellValue(list.get(i).getLevel());
            row1.createCell(3).setCellValue(list.get(i).getDisplayOrder());
            row1.createCell(4).setCellValue(list.get(i).getSubTitle());
            row1.createCell(5).setCellValue(list.get(i).getType());
            row1.createCell(6).setCellValue(list.get(i).getEnable());
        }
        return workbook;
    }
    @Resource
    private QuestionDao questionDao;

    @Override
    public List<Map<String, Object>> countQuestion() {
        QueryWrapper<QuestionEntity> questionEntityQueryWrapper = new QueryWrapper<>();
        questionEntityQueryWrapper.select("TYPE,count(TYPE) as num").groupBy("type");
        List<Map<String, Object>> mapList = questionDao.selectMaps(questionEntityQueryWrapper);
        return mapList;
    }


}